package com.ruoyi.mes.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mes.domain.*;
import com.ruoyi.mes.mapper.*;
import com.ruoyi.mes.service.IOuthouInfoService;
import com.ruoyi.mes.service.IProInfoService;
import com.ruoyi.mes.utils.CodeUtils;
import com.ruoyi.mes.utils.RepeatUtils;
import com.ruoyi.mes.vo.product.ProOrderVo;
import com.ruoyi.mes.vo.product.ProOutHouVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.ruoyi.mes.service.IProOrderService;

import static com.ruoyi.common.core.domain.AjaxResult.DATA_TAG;

/**
 * 产品订单Service业务层处理
 *
 * @author LongAndHao
 * @date 2023-04-04
 */
@Service
public class ProOrderServiceImpl implements IProOrderService {

    @Autowired
    private IProInfoService proInfoService;

    @Autowired
    private IOuthouInfoService outhouInfoService;

    @Autowired
    private ProOrderMapper proOrderMapper;

    @Autowired
    private ProgPlanMapper progPlanMapper;

    @Autowired
    private ProStockMapper proStockMapper;

    @Autowired
    private HouInfoMapper houInfoMapper;

    @Autowired
    private OuthouInfoMapper outhouInfoMapper;


    /**
     * 查询产品订单
     *
     * @param id 产品订单主键
     * @return 产品订单
     */
    @Override
    public ProOrder selectProOrderById(Long id) {
        return proOrderMapper.selectProOrderById(id);
    }

    /**
     * 查询产品订单列表
     *
     * @param proOrder 产品订单
     * @return 产品订单
     */
    @Override
    public List<ProOrder> selectProOrderList(ProOrder proOrder) {
        return proOrderMapper.selectProOrderList(proOrder);
    }

    /**
     * 新增产品订单
     *
     * @param proOrder 产品订单
     * @return 结果
     */
    @Override
    public int insertProOrder(ProOrder proOrder) {
        proOrder.setCreateTime(DateUtils.getNowDate());
        return proOrderMapper.insertProOrder(proOrder);
    }

    /**
     * 修改产品订单
     *
     * @param proOrder 产品订单
     * @return 结果
     */
    @Override
    public int updateProOrder(ProOrder proOrder) {
        proOrder.setUpdateTime(DateUtils.getNowDate());
        return proOrderMapper.updateProOrder(proOrder);
    }

    /**
     * 批量删除产品订单
     *
     * @param ids 需要删除的产品订单主键
     * @return 结果
     */
    @Override
    public int deleteProOrderByIds(Long[] ids) {
        return proOrderMapper.deleteProOrderByIds(ids);
    }

    /**
     * 删除产品订单信息
     *
     * @param id 产品订单主键
     * @return 结果
     */
    @Override
    public int deleteProOrderById(Long id) {
        return proOrderMapper.deleteProOrderById(id);
    }

    /**
     * 增 - 产品订单
     *
     * @param proOrderVo
     * @return
     */
    @Override
    public AjaxResult saveOrder(ProOrderVo proOrderVo) {
        //产品编码判重
        if (RepeatUtils.isOrderNumberRepeat(proOrderMapper, proOrderVo)) {
            return AjaxResult.error("订单编码重复!");
        }

        //产品判重
        if (RepeatUtils.isProductRepeat(proOrderVo.getProInfoList())) {
            return AjaxResult.error("产品重复!");
        }

        List<ProInfo> proInfoList = proOrderVo.getProInfoList();
        if (proInfoList.size() == 0) {
            return AjaxResult.error("未选择产品！");
        }

        //判断产品是否已定义工艺及Bom
        for (ProInfo info : proInfoList) {
            ProInfo proInfo = proInfoService.selectProInfoById(info.getId());
            if (proInfo.getBomStatus() == 0 || proInfo.getTecStatus() == 0){
                return AjaxResult.error("产品未定义工艺或Bom！");
            }
        }

        for (ProInfo proInfo : proInfoList) {
            ProOrder proOrder = new ProOrder();
            BeanUtils.copyProperties(proOrderVo, proOrder);

            proOrder.setProId(proInfo.getId());
            proOrder.setOrderStatus(0L);
            proOrder.setOrderDemandNum(proInfo.getOrderDemandNum());
            proOrderMapper.insertProOrder(proOrder);

            //生成生产计划
            String progCode = CodeUtils.ProgCodeCreat();//生产计划编号

            ProgPlan progPlan = new ProgPlan();
            progPlan.setProgCode(progCode);
            progPlan.setOrderNumber(proOrderVo.getOrderNumber());
            progPlan.setProId(proInfo.getId());
//            progPlan.setProgCode(proInfo.getProCode());
            progPlan.setProName(proInfo.getProName());
            progPlan.setProType(proInfo.getProType());
            progPlan.setStatus(0L);//生产计划默认未下达
            progPlan.setProgQuantity(proInfo.getOrderDemandNum());
            progPlan.setRemark("测试数据");
            progPlanMapper.insertProgPlan(progPlan);
        }

        return AjaxResult.success("新增成功!");
    }

    /**
     * 删 - 产品订单 - id
     *
     * @param orderId
     * @return
     */
    @Override
    public AjaxResult deleteByOrderId(Long orderId) {
        ProOrder proOrder = proOrderMapper.selectProOrderById(orderId);
        ProOrder order = new ProOrder();
        order.setOrderNumber(proOrder.getOrderNumber());
        List<ProOrder> proOrders = proOrderMapper.selectProOrderList(order);
        for (ProOrder proOrder1 : proOrders) {
            proOrderMapper.deleteProOrderById(proOrder1.getId());
        }
        return AjaxResult.success("删除成功!");
    }

    /**
     * 改 - 产品订单 (先删后增)
     *
     * @param proOrderVo
     * @return
     */
    @Override
    public AjaxResult editProOrder(ProOrderVo proOrderVo) {
        //获取生产计划id
        ProOrder order = selectProOrderById(proOrderVo.getId());
//        String progId = order.getProgId();
        //删
        deleteByOrderId(proOrderVo.getId());
        //增
        for (ProInfo proInfo : proOrderVo.getProInfoList()) {
            ProOrder proOrder = new ProOrder();
            BeanUtils.copyProperties(proOrderVo, proOrder);
//            proOrder.setProgId(progId);//生产计划id

            proOrder.setProId(proInfo.getId());
            proOrder.setOrderStatus(0L);
            proOrder.setOrderDemandNum(proInfo.getOrderDemandNum());
            proOrderMapper.insertProOrder(proOrder);
        }
        return AjaxResult.success("修改成功!");
    }

    /**
     * 查 - 产品订单详情 - id
     *
     * @param orderId
     * @return
     */
    @Override
    public AjaxResult getDetails(Long orderId) {
        ProOrderVo proOrderVo = new ProOrderVo();
        ProOrder order = selectProOrderById(orderId);
        BeanUtils.copyProperties(order, proOrderVo);

        ProOrder proOrder = new ProOrder();
        proOrder.setOrderNumber(order.getOrderNumber());
        ArrayList<ProInfo> proInfos = new ArrayList<>();
        List<ProOrder> proOrders = selectProOrderList(proOrder);
        for (ProOrder proOrder1 : proOrders) {
            ProInfo proInfo = proInfoService.selectProInfoById(proOrder1.getProId());
            proInfo.setOrderDemandNum(proOrder1.getOrderDemandNum());
            proInfo.setOrderStatus(proOrder1.getOrderStatus());
            proInfos.add(proInfo);
        }
        proOrderVo.setProInfoList(proInfos);
        return AjaxResult.success(proOrderVo);
    }

    /**
     * 查 - 产品订单分页 - 不重复订单编码
     *
     * @param proOrder
     * @return
     */
    @Override
    public List<ProOrder> selectDistinctOrders(ProOrder proOrder) {
        List<ProOrder> proOrderList = proOrderMapper.selectDistinctOrders(proOrder);
        if (proOrderList.size() != 0){
            for (ProOrder order : proOrderList) {
                List<ProOrder> proOrders = proOrderMapper.selectProOrdersByCode(order.getOrderNumber());

                int count1 = 0;
                for (ProOrder proOrder1 : proOrders) {
                    count1 += proOrder1.getOrderStatus();
                }

                if (count1 < proOrders.size() && count1 != 0) {
                    order.setStatus(1L);
                } else if (count1 == 0) {
                    order.setStatus(0L);
                } else {
                    order.setStatus(2L);
                }
            }
        }
        return proOrderList;
    }

    /**
     * 产品出库
     *
     * @param proOutHouVo
     * @return
     */
    @Override
    public AjaxResult proOuthou(ProOutHouVo proOutHouVo) {
        for (Long id : proOutHouVo.getIds()) {

            int flag = 0;//库存产品存在订单标志 0 - 不存在 1- 存在

            //获取产品库存
            ProStock proStock = proStockMapper.selectProStockById(id);
            //获取订单的详情
            ProOrder order = selectProOrderById(proOutHouVo.getProOrderId());
            ProOrder proOrder = new ProOrder();
            proOrder.setOrderNumber(order.getOrderNumber());
            List<ProOrder> proOrders = selectProOrderList(proOrder);

            for (ProOrder proOrder1 : proOrders) {
                //若选择的产品库存在订单内，则更新产品库存数量，库房剩余容量,更新产品订单状态为已完成  新增产品出库信息
                ProInfo proInfo = proInfoService.selectProInfoById(proOrder1.getProId());
                if (proInfo.getProCode().equals(proStock.getProCode())) {
                    flag = 1;//更新标志

                    //若产品数量不足，则提示错误
                    if (proStock.getProQuantity() < proOrder1.getOrderDemandNum()) {
                        return AjaxResult.error(proStock.getProName() + "库存数量不足!");
                    }

//                    coderChen:此处需要修改
                    //更新产品库存
                    proStock.setProQuantity(proStock.getProQuantity() - proOrder1.getOrderDemandNum());
                    proStockMapper.updateProStock(proStock);

                    //更新库房剩余容量
                    HouInfo houInfo = houInfoMapper.selectHouInfoByHouId(proStock.getHouId());
                    if (houInfo.getHouRemainCapacity() + proOrder1.getOrderDemandNum() > houInfo.getHouCapacity()){
                        houInfo.setHouRemainCapacity(houInfo.getHouCapacity());
                    }
                    houInfo.setHouRemainCapacity(houInfo.getHouRemainCapacity() + proOrder1.getOrderDemandNum());
                    houInfoMapper.updateHouInfo(houInfo);

                    //更新产品订单状态
                    proOrder1.setOrderStatus(1L);
                    proOrderMapper.updateProOrder(proOrder1);

                    //新增产品出库信息
                    OuthouInfo outhouInfo = new OuthouInfo();
                    outhouInfo.setOrderNumber(proOrder1.getOrderNumber());
                    outhouInfo.setOuthouPerson(SecurityUtils.getLoginUser().getUser().getNickName());
                    outhouInfo.setOuthouDate(proOutHouVo.getOuthouDate());
                    outhouInfo.setProCode(proInfo.getProCode());
                    outhouInfo.setProName(proInfo.getProName());
                    outhouInfo.setProQuantity(proOrder1.getOrderDemandNum());
                    outhouInfo.setRemark("测试数据");
                    outhouInfoMapper.insertOuthouInfo(outhouInfo);
                }
            }

            if (flag == 0) {
                return AjaxResult.error("非订单产品，不能出货!");
            }

        }
        return AjaxResult.success("出库成功!");
    }

    /**
     * 查 - 订单出库信息
     * @param orderNumber 订单编号
     * @return
     */
    @Override
    public AjaxResult getOutHouInfo(String orderNumber) {
        OuthouInfo outhouInfo = new OuthouInfo();
        outhouInfo.setOrderNumber(orderNumber);
        List<OuthouInfo> outhouInfos = outhouInfoService.selectOuthouInfoList(outhouInfo);
        return AjaxResult.success("查询成功",outhouInfos);
    }

    /**
     * 上一周订单数
     * @return
     */
    public List<Map<String,Long>> lastWeekProOrders(Date startTime, Date endTime) {
        return proOrderMapper.lastWeekProOrders(startTime,endTime);
    }
}
